<?php

namespace App\Models;

use App\Events\OrderPaySuccess;
use App\Logic\UserBuyLogic;
use App\User;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Carbon;

class UserBuyOrder extends Model
{
    protected $table = 'user_buy_order';

    protected $guarded = [];


    public function liveroom()
    {
        return $this->belongsTo(Liveroom::class, 'liveroom_id');
    }

    public function liveroom_log()
    {
        return $this->hasOne(MoneyLog::class, 'id', 'liveroom_log_id');
    }

    public function l_user()
    {
        return $this->belongsTo(User::class, 'l_user_id');
    }

    public function user()
    {
        return $this->belongsTo(User::class, 'user_id');
    }

    public function tg_user()
    {
        return $this->belongsTo(User::class, 'tg_user_id');
    }

    public function item()
    {
        return $this->morphTo();
    }


    public static function getOrderSn()
    {
        return date('Ymd') . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 10);
    }

    public static function paySuccess($order_sn, $pay_sn)
    {
        $order = self::query()->where('order_sn', $order_sn)->first();
        if (empty($order)) {
            return [false, "Order not exist."];
        }
        if ($order->pay_state == 1) {
            return [true, "pay success"];
        }
        $order->pay_state = 1;
        $order->order_state = 1;
        $order->pay_sn = $pay_sn;
        $order->pay_time = Carbon::now()->toDateTimeString();
        $order->save();
        //创建购买标识
        $user_buy = UserBuy::query()->create([
            'item_id' => $order->item_id,
            'item_type' => $order->item_type,
            'user_id' => $order->user_id,
            'order_id' => $order->id,
            'end_time' => 0,
            'liveroom_id' => $order->liveroom_id,
            'l_user_id' => $order->l_user_id,
        ]);
        $order->user_buy_id = $user_buy->id;
        $order->save();
        //其他事件
        //TODO
        event(new OrderPaySuccess($order));
        //返回
        return [true, "pay success"];

    }

    /**
     * @param string $type 产品类型
     * @param object $item 产品对象
     * @param int $quantity 购买数量
     * @param User $user 购买用户对象
     * @param bool|object $coupons 优惠券对象
     * @param bool|object $qd 渠道对象
     * @param bool|User $tg_user 推广用户对象
     * @return array 返回订单对象
     */
    public static function createOrder($type, $item, $quantity, $user, $coupons = false, $qd = false, $tg_user = false)
    {
        //计算订单金额
        list($item_money, $order_money, $pay_money, $coupons_id, $coupons_money) = self::_getOrderMoney($type, $item, $quantity, $coupons);

        //计算分润金额
        list($qd_id, $qd_money, $liveroom_id, $l_user_id, $liveroom_money, $tg_user_id, $tg_money, $tg_level, $share_money, $system_money) = self::_getShareMoney($type, $item, $order_money, $pay_money, $qd, $tg_user);


        $order = self::query()->create([
            'order_sn' => self::getOrderSn(),
            'user_id' => $user->id,
            'item_type' => $type,
            'item_id' => $item->id,
            'item_money' => $item_money,
            'quantity' => $quantity,
            'order_money' => $order_money,
            'pay_money' => $pay_money,
            'coupons_id' => $coupons_id,
            'coupons_money' => $coupons_money,
            'qd_id' => $qd_id,
            'qd_money' => $qd_money,
            'qd_log_id' => 0,
            'liveroom_id' => $liveroom_id,
            'l_user_id' => $l_user_id,
            'liveroom_money' => $liveroom_money,
            'tg_user_id' => $tg_user_id,
            'tg_money' => $tg_money,
            'tg_level' => $tg_level,
            'pay_state' => 0,
            'order_state' => 0,
            'liveroom_log_id' => 0,
            'tg_log_id' => 0,
            'user_buy_id' => 0,
            'share_money' => $share_money,
            'system_money' => $system_money,
        ]);
        return [true, $order];
    }

    /**
     * 计算各平台分润金额
     * @param $type
     * @param $item
     * @param $order_money
     * @param $pay_money
     * @param $qd
     * @param $tg_user
     * @return array
     */
    private static function _getShareMoney($type, $item, $order_money, $pay_money, $qd, $tg_user)
    {
        $liveroom = $item->user->liveroom;

        $commission = $item->resell_enabled == 1 ? $pay_money * ($item->resell_percent / 100) : 0;
        if ($commission > 0 && $commission < $pay_money) {
            if ($qd && $tg_user) {//如果渠道和用户同时分佣
                $qd_id = $qd->id;
                $qd_money = $commission * (10 / 100);
                $tg_user_id = $tg_user->id;
                $tg_money = $commission * (90 / 100);
                $tg_level = 1;
            } elseif ($qd && !$tg_user) {
                $qd_id = $qd->id;
                $qd_money = $commission;
                $tg_user_id = 0;
                $tg_money = 0;
                $tg_level = 0;
            } elseif (!$qd && $tg_user) {
                $qd_id = 0;
                $qd_money = 0;
                $tg_user_id = $tg_user->id;
                $tg_money = $commission;
                $tg_level = 1;
            } else {
                $qd_id = 0;
                $qd_money = 0;
                $tg_user_id = 0;
                $tg_money = 0;
                $tg_level = 0;
            }
        } else {
            $qd_id = 0;
            $qd_money = 0;
            $tg_user_id = 0;
            $tg_money = 0;
            $tg_level = 0;
        }


        $liveroom_id = $liveroom->id;
        $l_user_id = $liveroom->user_id;
        $liveroom_money = $pay_money - $qd_money - $tg_money;

        $share_money = $qd_money + $liveroom_money + $tg_money;

        $system_money = $pay_money - $share_money;
        return [$qd_id, $qd_money, $liveroom_id, $l_user_id, $liveroom_money, $tg_user_id, $tg_money, $tg_level, $share_money, $system_money];
    }


    /**
     * 计算当前订单金额
     * @param $type
     * @param $item
     * @param $coupons
     * @return array
     */
    private static function _getOrderMoney($type, $item, $quantity, $coupons)
    {
        $item_money = $item->money;
        $order_money = $item_money;
        $pay_money = $item_money;
        return [$item_money, $order_money, $pay_money, 0, 0];

    }


    /**
     * @param $type
     * @param $item_id
     * @return bool|\Illuminate\Database\Eloquent\Collection|Model
     */
    public static function _getItem($type, $item_id)
    {
        $item = false;
        switch ($type) {
            case Doc::class:
                $item = Doc::query()->findOrFail($item_id);
                break;
        }

        return $item;
    }


    public static function _checkItemBuyState($type, $item, $user)
    {
        $user_buy_state = false;
        switch ($type) {
            case Doc::class:
                $user_buy_state = UserBuyLogic::judgeDoc($item, $user);
                break;
            case 'lecture':
                $user_buy_state = UserBuyLogic::judgeLecture($item, $user);
                break;
            case 'channel':
                $user_buy_state = UserBuyLogic::judgeChannel($item, $user);
                break;
        }
        if ($item->user_id == $user->id) {
            return [false, '无法购买自己的产品'];
        }
        if (!$user_buy_state) {
            return [false, '数据异常'];
        }
        //检测状态
        if ($item->approved == 0) {
            return [false, '产品已下架'];
        }
        //检测购买
        if ($user_buy_state->getIsBuy()) {
            return [false, '产品已购买'];
        } elseif ($user_buy_state->getIsShow()) {
            return [false, '产品无需购买'];
        } else {
            return [true, '可以购买'];
        }

    }

    const PAY_STATE = [
        0 => '未支付',
        1 => '已支付'
    ];

    const ORDER_CLOSE = 3;

    const ORDER_STATE = [
        0 => '未支付',
        1 => '已支付',
        2 => '已退款',
        3 => '已关闭'
    ];
}
